package com.qersoft.controller;

import com.qersoft.entity.ExamRecord;
import com.qersoft.service.ExamRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;

@RestController
@RequestMapping("/exam-record")
public class ExamRecordController {

    @Autowired
    private ExamRecordService examRecordService;

    /**
     * 根据考试记录 ID 查询考试记录
     *
     * @param examRecordId 考试记录 ID
     * @return 返回考试记录
     */
    @GetMapping("/{examRecordId}")
    public ResponseEntity<?> getExamRecordById(@PathVariable Long examRecordId) {
        ExamRecord examRecord = examRecordService.getExamRecordById(examRecordId);
        if (examRecord == null) {
            return ResponseEntity.status(404).body("考试记录不存在");
        }
        return ResponseEntity.ok(examRecord);
    }

    /**
     * 根据学生 ID 查询所有考试记录
     *
     * @param studentId 学生 ID
     * @return 返回学生的所有考试记录
     */
    @GetMapping("/student/{studentId}")
    public ResponseEntity<?> getExamRecordsByStudentId(@PathVariable Long studentId) {
        List<ExamRecord> examRecords = examRecordService.getExamRecordsByStudentId(studentId);
        if (examRecords.isEmpty()) {
            return ResponseEntity.status(404).body("没有找到该学生的考试记录");
        }
        return ResponseEntity.ok(examRecords);
    }

    /**
     * 创建新的考试记录
     *
     * @param examRecord 考试记录实体
     * @return 返回创建的考试记录
     */
    @PostMapping("/")
    public ResponseEntity<?> createExamRecord(@RequestBody ExamRecord examRecord) {
        boolean isCreated = examRecordService.addExamRecord(examRecord);
        if (isCreated) {
            return ResponseEntity.status(201).body(examRecord);  // 201 Created
        } else {
            return ResponseEntity.status(500).body("创建考试记录失败");
        }
    }

    /**
     * 更新考试记录的分数
     *
     * @param examRecordId 考试记录 ID
     * @param score        新的分数
     * @return 返回更新后的考试记录
     */
    @PutMapping("/{examRecordId}/score")
    public ResponseEntity<?> updateScore(@PathVariable Long examRecordId, @RequestParam BigDecimal score) {
        boolean isUpdated = examRecordService.updateScore(examRecordId, score);
        if (isUpdated) {
            return ResponseEntity.ok("考试记录分数更新成功");
        } else {
            return ResponseEntity.status(404).body("考试记录未找到，更新失败");
        }
    }

    /**
     * 删除考试记录
     *
     * @param examRecordId 考试记录 ID
     * @return 返回删除状态
     */
    @DeleteMapping("/{examRecordId}")
    public ResponseEntity<?> deleteExamRecord(@PathVariable Long examRecordId) {
        boolean isDeleted = examRecordService.deleteExamRecord(examRecordId);
        if (isDeleted) {
            return ResponseEntity.ok("考试记录删除成功");
        } else {
            return ResponseEntity.status(404).body("考试记录未找到，删除失败");
        }
    }
}
